//
//  AppointmentDetailsViewController.m
//  Doctor1.0
//
//  Created by mk on 15/11/5.
//  Copyright (c) 2015年 cocoa-mk. All rights reserved.
//

#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

#import "AppointmentDetailsViewController.h"


@interface AppointmentDetailsViewController ()
{
    NSInteger updateIndex;
    
    NSMutableArray * arrayDetPicker;//当前的
    NSMutableDictionary * dicData;
    NSInteger deleteImageIndex;//需要删除的图片
    
    BOOL nowShowUpdate;//当前是上传图片view
}


@end

@implementation AppointmentDetailsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    nowShowUpdate = NO;
    
    arrayDetPicker = [[NSMutableArray alloc]initWithCapacity:0];
    dicData = [[NSMutableDictionary alloc]initWithCapacity:0];
    
    titleLabel.text = @"预约单详情";

    [scrollMain setAlwaysBounceVertical:YES];
    //预约单详情
    [self getDetailsData];
    //[self loadPicturData];
}


-(void)getDetailsData
{
    NSString * strUrl = [NSString stringWithFormat:@"%@?username=%@&token=%@",self.reservationData.actionUrl,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token]];
    
    SetHUDShowText(@"加载中..")
    [[HttpClient manager]GET:strUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        SetHUDHidden;
        if([[responseObject objectForKey:requestDataKey] isKindOfClass:[NSDictionary class]])
        {
           [dicData addEntriesFromDictionary:[responseObject objectForKey:requestDataKey]];
           if ([[dicData objectForKey:@"files"] isKindOfClass:[NSArray class]])
           {
             [arrayDetPicker addObjectsFromArray:[dicData objectForKey:@"files"]];
           }
           [self setViewWithData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view);
    }];
}

/*
-(void)loadPicturData
{
    NSString * strUrl = [NSString stringWithFormat:@"http://192.168.31.118/file.myzd.com/api/fileurl?tableName=%@&username=%@&token=%@&bookingId=%@",APPOINTtableName,[gProjConfig.dicUserData objectForKey:USER_tel],[gProjConfig.dicUserData objectForKey:USER_token],self.reservationData.dataID];
    
    [[HttpClient manager]GET:strUrl
                  parameters:nil
                     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"loadPicturData==%@",responseObject);
         id requestData = [responseObject objectForKey:requestDataKey];
         if ([requestData isKindOfClass:[NSDictionary class]])
         {
             id files = [requestData objectForKey:@"files"];
             if ([files isKindOfClass:[NSArray class]])
             {
                 arrayDetPicker = [[responseObject objectForKey:requestDataKey] objectForKey:@"files"];
                 [self setDefaultPickerView];
             }
         }else if ([requestData isKindOfClass:[NSArray class]])
         {
             arrayDetPicker = [responseObject objectForKey:requestDataKey];
             [self setDefaultPickerView];//默认显示下载的图片
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         HUDShowRequestError(error.domain, self.view)
     }];
}
*/


-(void)setViewWithData
{
    btnUpdatePicker.hidden = NO;
    [self setDefaultPickerView];//默认显示下载的图片
    
    labrefNo.text = NullObjToString([dicData objectForKey:@"refNo"]);//订单号id
    //user
    labUserName.text = NullObjToString([dicData objectForKey:@"patientName"]);
    labUserTel.text = NullObjToString([dicData objectForKey:@"mobile"]);
    labHPName.text = NullObjToString([dicData objectForKey:@"hospitalName"]);//医院
    
    //
    labKSName.text = NullObjToString([dicData objectForKey:@"hpDeptName"]);//科室名字
    labDoctorName.text = NullObjToString([dicData objectForKey:@"expertName"]);
    if (NullObjToString([dicData objectForKey:@"dateStart"]).length>0 && NullObjToString([dicData objectForKey:@"dateEnd"]).length>0)
    {
        
        NSString * strBegdate = [CommonFunctions nianYueRiStringConvertDateString:[dicData objectForKey:@"dateStart"] withFormatter:@"-"];
        
        NSString * strEnddate = [CommonFunctions nianYueRiStringConvertDateString:[dicData objectForKey:@"dateEnd"] withFormatter:@"-"];
        
       labTime.text = [NSString stringWithFormat:@"%@至%@",strBegdate,strEnddate];//
    }else
    {
       labTime.text = @"";
    }
    //病例
    labExpertDetails.text =  NullObjToString([dicData objectForKey:@"diseaseDetail"]);//病例详情
    labExpertName.text =  NullObjToString([dicData objectForKey:@"diseaseName"]);//病例名字
 
}


-(void)setDefaultPickerView
{
    btnOK.hidden = !nowShowUpdate;
    
    for(UIView * imageP in [viewDefaultPick subviews])
    {
        [imageP removeFromSuperview];
    }
   
    int btnWidth = (appScreenWidth-60)/3;
    
    int pickerViewH = 0;
    if (arrayDetPicker.count <= 3 && arrayDetPicker.count > 0)
            pickerViewH = btnWidth+10;
    else if (arrayDetPicker.count <= 6 && arrayDetPicker.count > 3)
            pickerViewH = btnWidth*2+20;
    else if (arrayDetPicker.count > 6)
            pickerViewH = btnWidth*3+30;
    
    for (NSLayoutConstraint *constraints in [viewDefaultPick constraints])
    {
        if (constraints.firstItem == viewDefaultPick && constraints.firstAttribute == NSLayoutAttributeHeight)
        {
            constraints.constant = pickerViewH;
            break;
        }
    }


    //设置view的高度
    
    int viewWidth = APP_CONTENT_WIDTH;
    
    int btnHeight = (appScreenWidth-60)/3;
    int rowNum = 0;
    int rowRight = 15;
    for (int i = 0; i < [arrayDetPicker count]; i++)
    {
        UIButton *btnMark = [UIButton buttonWithType:UIButtonTypeCustom];
        btnMark.tag = i;
        [btnMark addTarget:self action:@selector(btnLookImage:) forControlEvents:UIControlEventTouchUpInside];
        if (!nowShowUpdate)
        {
            NSString * strImageUrl = [NSString stringWithFormat:@"%@",[[arrayDetPicker objectAtIndex:i] objectForKey:@"absThumbnailUrl"]];
            [self setButtonImageWithButton:btnMark iamgePathUrl:strImageUrl];
        }else
        {
            [btnMark setBackgroundImage:[arrayDetPicker objectAtIndex:i] forState:UIControlStateNormal];
        }

        btnMark.userInteractionEnabled = YES;
        [btnMark setTranslatesAutoresizingMaskIntoConstraints:NO];
        [viewDefaultPick addSubview:btnMark];
        
        NSDictionary *views = NSDictionaryOfVariableBindings(btnMark);
        NSString *sH = [NSString stringWithFormat:@"H:|-%d@1000-[btnMark(%d@1000)]",rowRight,btnWidth];
        [viewDefaultPick addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:sH
                                                                              options:0
                                                                              metrics:nil
                                                                                views:views]];
        
        NSString *sV = [NSString stringWithFormat:@"V:|-%d@1000-[btnMark(%d@1000)]",rowNum*(btnHeight+7),btnHeight];
        if (i == [arrayDetPicker count]-1) {
            sV = [NSString stringWithFormat:@"V:|-%d@1000-[btnMark(%d@1000)]-0@1000-|",rowNum*(btnHeight+7),btnHeight];
        }
        [viewDefaultPick addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:sV
                                                                              options:0
                                                                              metrics:nil
                                                                                views:views]];
        rowRight += (btnWidth+15.0f);
        if (rowRight+btnWidth > viewWidth) {
            rowRight = 15.0f;
            rowNum++;
        }
    }
    
      [viewDefaultPick.superview layoutIfNeeded];
}

#pragma mark ===查看病例大图图片===
-(void)btnLookImage:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    MFMWPhotoBrowser * browse = [[MFMWPhotoBrowser alloc] init];
    browse.mfDelegate = self;
    browse.delegate = self;
    browse.displayDeleteButton = (nowShowUpdate?YES:NO);
    [browse setCurrentPhotoIndex:btn.tag];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browse];
    [self presentViewController:nc animated:YES completion:nil];
    
}


#pragma mark 添加继续图片
-(IBAction)btnAddImage:(id)sender
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"选照片",@"拍照", nil];
    [sheet showInView:self.view];
}


#pragma mark 确定上传
-(IBAction)btnUpdateImageData:(id)sender
{
    [self updateImage];
}

#pragma mark 上传图片
-(void)updateImage
{
    if (arrayDetPicker.count == 0)
    {
        Alert(alerTitle, @"没有可以上传的图片", @"确定")
        return;
    }
    
    
    updateIndex = 0;
    for (int i = 0; i < arrayDetPicker.count; i++)
    {
        SetHUDStartText(@"上传图片中..")
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
        [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"bookingFile[username]"];
        [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"bookingFile[token]"];
        [dic setObject:self.reservationData.dataID forKey:@"bookingFile[booking_id]"];
        
        [[HttpClient manager]UPLOADIMAGE:@"/bookingfile"
                             uploadImage:[arrayDetPicker objectAtIndex:i]
                              parameters:dic
                                 success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             if (updateIndex == (arrayDetPicker.count-1))
             {
                 SetHUDFinishedText(@"上传成功")
                 return;
             }
             updateIndex = updateIndex+1;
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view);
         }];

        
        /*
        NSString * strGetToken = [NSString stringWithFormat:@"http://192.168.31.118/file.myzd.com/api/uploadtoken?tableName=%@",APPOINTtableName];
        
        NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
        long long int currentTime=(long long int)time;
        NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
        NSData *imageData = UIImageJPEGRepresentation([arrayDetPicker objectAtIndex:updateIndex],1);
        
        [[HttpClient manager]UPLOADIMAGEQINIU:strGetToken
                                  uploadImage:[arrayDetPicker objectAtIndex:i]
                              uploadImageName:[NSString stringWithFormat:@"ImageName%@.jpg",tempTime]
                                   parameters:nil
                                      success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             //向服务器提交数据
             DLog(@"==%@",responseObject);
             
             if ([responseObject isKindOfClass:[NSDictionary class]])
             {
                 NSInteger length = [imageData length]/1000;
                 
                 NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:0];
                 [dic setObject:APPOINTtableName forKey:@"appFile[tableName]"];
                 
                 [dic setObject:[NSString stringWithFormat:@"%ld",(long)length] forKey:@"appFile[size]"];
                 [dic setObject:@"jpg" forKey:@"appFile[type]"];
                 
                 [dic setObject:NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"remoteDomain"]) forKey:@"appFile[remoteDomain]"];//地址url
                 [dic setObject:NullObjToString([[responseObject objectForKey:requestDataKey] objectForKey:@"reomteKey"]) forKey:@"appFile[remoteKey]"];
                 
                 [dic setObject:[dicData objectForKey:@"id"] forKey:@"appFile[bookingId]"];
                 
                 [dic setObject:[gProjConfig.dicUserData objectForKey:USER_tel] forKey:@"appFile[username]"];
                 [dic setObject:[gProjConfig.dicUserData objectForKey:USER_token] forKey:@"appFile[token]"];
                 
                 if (updateIndex == (arrayDetPicker.count-1))  //3
                 {
                     [self updateData:dic isEnd:YES];
                 }
                 else
                 {
                     [self updateData:dic isEnd:NO];
                 }
                 
                 updateIndex = updateIndex+1;
             }
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             SetHUDHidden;
             HUDShowRequestError(error.domain, self.view);
         }];
         */
    }
}

/*
#pragma mark 七牛上传成功 数据保存至数据库接口
-(void)updateData:(NSMutableDictionary *)requestDic isEnd:(BOOL)end
{

    NSString * strUpdateUrl = @"http://192.168.31.118/file.myzd.com/api/saveappfile";
    DLog(@"==%@",requestDic);
    
    [[HttpClient manager]POST:strUpdateUrl
                   parameters:requestDic
                      success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         DLog(@"=上传图片成功后回调=%@",responseObject);
         if (end)
         {
             SetHUDFinishedText(@"上传成功")
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         SetHUDHidden;
         HUDShowRequestError(error.domain, self.view);
     }];
}
*/
-(void)hudWasHidden:(MBProgressHUD *)hud
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark =======delegate======

#pragma mark photoBrowerNeedDeletePhoto
- (void)photoBrowerNeedDeletePhoto:(MFMWPhotoBrowser *)photoBrowser AtIndex:(int)index
{
    [arrayDetPicker removeObjectAtIndex:index];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self setDefaultPickerView];//更新上传图片的view
}

//查看大图
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
//    if(showUpdatePickerView)
//        return arrayUpdatePicker.count;
//    else
    return arrayDetPicker.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    MWPhoto * photo ;
    
    if (!nowShowUpdate)//表示数组存放的是下载的图片!
    {
        NSString * strUrl = [NSString stringWithFormat:@"%@",[[arrayDetPicker objectAtIndex:index] objectForKey:@"absFileUrl"]];
        photo = [MWPhoto photoWithURL:[NSURL URLWithString:strUrl]];
    }
    else//表示数组存放的是重新添加的图片
    {
       photo = [MWPhoto photoWithImage:[arrayDetPicker objectAtIndex:index]];
    }
    return photo;
    
}

#pragma mark actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
            {
                //无权限
                Alert(alerTitle, @"您的设备不允许[名医主刀]访问您的'相机',请到'设置'里面找到[名医主刀]并打开允许[名医主刀]访问'相机'功能", @"确定")
                return;
            }
            UIImagePickerController * picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;  //相机
            [self presentViewController:picker animated:YES completion:nil];
            
        }else
        {
            Alert(alerTitle, @"您的设备无法使用'相机'", @"确定")
        }

    }else if (buttonIndex == 0)
    {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
              ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
              if (author == kCLAuthorizationStatusRestricted || author ==kCLAuthorizationStatusDenied)
              {
                //无权限
                Alert(alerTitle, @"您的设备不允许[名医主刀]访问您的'照片',请到'设置'里面找到[名医主刀]并打开允许[名医主刀]访问'照片'功能", @"确定")
                return;
               }
            
            QBMFImagePickerController *selectPhoto = [[QBMFImagePickerController alloc] init];
            selectPhoto.QBMFDelegate = self;
            selectPhoto.maximumNumberOfSelection = (9 - [arrayDetPicker count]);
            [self presentViewController:selectPhoto animated:YES completion:nil];

        }else
        {
            Alert(alerTitle, @"您的设备无法使用'照片'", @"确定")
        }
    }
}

#pragma mark - 选择照片发送协议方法 QBMFImagePickerController
- (void)imagePickerController:(QBMFImagePickerController *)imagePickerController didSelectPhtos:(NSArray *)photos
{
    if (!nowShowUpdate)//当前显示的是默认的图片view
    {
        [arrayDetPicker removeAllObjects];
    }
     [arrayDetPicker addObjectsFromArray:photos];
     nowShowUpdate = YES;
     [self setDefaultPickerView];
}


//====================

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    if (image)
    {
        if (!nowShowUpdate)//当前显示的是默认的图片view
        {
           [arrayDetPicker removeAllObjects];
        }
        [arrayDetPicker addObject:image];
        nowShowUpdate = YES;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    [self setDefaultPickerView];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex == buttonIndex)
    {
        [arrayDetPicker removeObjectAtIndex:deleteImageIndex];//删除照片
        [self setDefaultPickerView];
        
    }


}




#pragma mark 加载图标
- (void)setButtonImageWithButton:(UIButton*) button iamgePathUrl:(NSString*)urlString
{
    [button setBackgroundImage:loadImageDefaule forState:UIControlStateNormal];
    
    NSURL* picurl = [NSURL URLWithString:urlString];
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    BOOL isMemory = NO;
    UIImage* imageMemory = [[manager imageCache] imageFromMemoryCacheForKey:picurl.absoluteString];
    if (imageMemory) { isMemory = YES;}
    [button.imageView sd_setImageWithURL:urlString placeholderImage:loadImageDefaule completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
     {
         if (image)
         {
             [button setBackgroundImage:image forState:UIControlStateNormal];
             if (!isMemory)
             {
                 [button setBackgroundImage:image forState:UIControlStateNormal];
             }
             
         }
     }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
